/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.diplomka.webapp;

import cz.muni.fi.diplomka.servicelayer.dto.Player;
import cz.muni.fi.diplomka.servicelayer.gamelogic.manager.PlayerManager;
import cz.muni.fi.diplomka.servicelayer.gamelogic.managerimpl.PlayerManagerImpl;
import cz.muni.fi.diplomka.servicelayer.util.Crypto;
import cz.muni.fi.diplomka.webapp.city.CityPage;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.Model;

/**
 *
 * @author Jakub Kutil
 */
public class HomePage extends WebPage {

    private PlayerManager playerManager = new PlayerManagerImpl();

    public HomePage() {
        add(new FeedbackPanel("feedback"));


        final TextField<String> nickname = new TextField<>("nickname",
                Model.of(""));

        final PasswordTextField password = new PasswordTextField("password",
                Model.of(""));
        //for properties file
        password.setLabel(Model.of("Password"));


        Form<?> form = new Form<Void>("form") {
            @Override
            protected void onSubmit() {
                Player player = playerManager.findPlayerByLogin(nickname.getValue());
                if (player.getNickName() != null) {
                    try {
                        if (Crypto.encode(password.getValue()).equals(player.getHashedPassword())) {
                            PageParameters pageParameters = new PageParameters();
                            pageParameters.add("id", player.getId().toString());
                            setResponsePage(CityPage.class, pageParameters);
                        } else {
                            error("Wrong password.");
                        }
                    } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
                        Logger.getLogger(HomePage.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } else {
                    error("Nickname not found. Are you registered?");
                }

            }
        };

        add(form);
        form.add(nickname);
        form.add(password);
    }
}
